package com.hmdp.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@RequiredArgsConstructor
public class RedisIdWorker {
    private static final long BEGIN_TIMESTAMP = 1735689600L; // 2025-01-01 00:00:00
    private final StringRedisTemplate stringRedisTemplate;

    public long createId(String key) {
        //根据当前时间 - 开始时间生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMP;
        //根据redis自增生成后32位
        String datePrefix = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd:"));
        //拼接redisKey
        String redisKey = "icr:" + datePrefix + key;
        Long increment = stringRedisTemplate.opsForValue().increment(redisKey);
        // 拼接
        return timestamp << 32 | increment;
    }
}
